package kr.ac.kaist.vrowser;

import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class UrlEditActivity extends VrowserBaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_urledit);

		app.getTextToSpeech().speak(
				getResources().getString(R.string.urlDescription),
				TextToSpeech.QUEUE_FLUSH, null);

		final EditText urlEditText = (EditText) this.findViewById(R.id.goURL);
		urlEditText.setText("");

		urlEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				if (hasFocus) {
					InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					keyboard.showSoftInput(urlEditText, 0);
				}

			}

		});

		urlEditText.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				keyboard.showSoftInput(urlEditText, 0);
				return false;
			}

		});

		urlEditText.setOnEditorActionListener(new OnEditorActionListener() {

			public boolean onEditorAction(TextView view, int actionId,
					KeyEvent event) {
				if ((event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
						|| event == null) {

					if (event != null
							&& (event.getAction() != KeyEvent.ACTION_DOWN))
						return false;
					InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

					in.hideSoftInputFromWindow(
							view.getApplicationWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
					String url = urlEditText.getText().toString();
					if (!url.startsWith("http")) {
						url = "http://".concat(url);
					}

					app.getWebController().getHTML(url);
					activity.finish();
					return true;
				}

				return false;
			}

		});

		urlEditText.requestFocus();

	}

	@Override
	protected void onStop() {
		super.onStop();
		activity.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		activity.finish();

	}
}
